# !/usr/bin/env python
# -*- coding: utf-8 -*-
import six.moves
from random import Random
from app.models.user import User
from app.util.md5 import md5_update


def get_tag(tag):
    if tag == 0 or tag == '0':
        return u'中性'
    elif tag == 1 or tag == '1':
        return u'利好'
    elif tag == -1 or tag == '-1':
        return u'利空'
    return u''


def get_abstract(content):
    if len(content) > 80:
        return u'%s...' % (content[:78],)
    else:
        return content


def get_user(_id=None, name=None):
    _user = None
    if _id is not None:
        _user = User.query.filter_by(id=_id).first()
    elif name is not None:
        _user = User.query.filter_by(name=name).first()
    if _user is None:
        return None
    if _user.is_delete:
        return None
    return _user


def create_salt(length=6):
    return random_str(length)


def create_pw(length=10):
    return random_str(length)


def random_str(length):
    s = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    len_chars = len(chars) - 1
    random = Random()
    for _ in six.moves.xrange(length):
        # 每次从chars中随机取一位
        s += chars[random.randint(0, len_chars)]
    return s


def add_user(name, is_admin=False):
    """
    添加用户
    :param name: 用户名
    :param is_admin: 是否为管理员
    :return: 用户密码
    """
    _user = User()
    _user.name = name
    _user.is_admin = is_admin
    pw = create_pw()
    _user.salt = create_salt()
    _user.password = md5_update(md5_update(pw), _user.salt)
    db_save(add_models=[_user])
    return pw


def del_user(name):
    """
    删除用户
    :param name: 用户名
    :return: 是否删除成功
    """
    _user = get_user(name=name)
    if _user is None:
        return False
    db_save(delete_models=[_user])
    return True


def reset_pw(name):
    """
    重置密码
    :param name: 用户名
    :return: 用户密码
    """
    _user = get_user(name=name)
    if _user is None:
        return None
    pw = create_pw()
    _user.salt = create_salt()
    _user.password = md5_update(md5_update(pw), _user.salt)
    _user.first_login = True
    db_save(add_models=[_user])
    return pw


def set_admin(name, is_admin):
    """
    设置管理员
    :param name: 用户名
    :param is_admin: 是否为管理员
    :return: 是否设置成功
    """
    _user = get_user(name=name)
    if _user is None:
        return False
    _user.is_admin = is_admin
    db_save(add_models=[_user])
    return True


def db_save(add_models=None, delete_models=None):
    from app import db
    if add_models:
        map(db.session.add, add_models)
    if delete_models:
        map(db.session.delete, delete_models)
    db.session.commit()


def check_pw(pw, salt, password):
    if password == md5_update(pw, salt):
        return True
    return False
